/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vacuela.phonecredits.servlet;

import com.vacuela.phonecredits.PhoneSynchronizerJob;

import com.vacuela.phonecredits.util.SynchUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.ee.servlet.QuartzInitializerListener;

/**
 *
 * @author Anita Cervantes
 */
public class PhoneCreditServlet extends HttpServlet {
    /*
    protected final Log log = LogFactory.getLog(getClass());
    private SynchUtils syn = null;
    private SchedulerFactory sf = null;
    private Scheduler sched = null;


    @Override
    public void init(ServletConfig cfg) throws javax.servlet.ServletException {
    super.init(cfg);

    log.info("Initi Phone Servlet Init ==> " + new Date());
    try {
    sf = new StdSchedulerFactory();
    sched = sf.getScheduler();

    syn = new SynchUtils();
    syn.openConnection();
    sched.getContext().put("utilClass", syn);


    //JOB
    JobDetail job = new JobDetail("JobTest1", "Group1", PhoneSynchronizerJob.class);
    log.info("Scheduel Job =>" + syn.getConfigParam("CronExpression"));
    CronTrigger trig = new CronTrigger("trigger1", "Group1", "JobTest1", "Group1", syn.getConfigParam("CronExpression"));


    sched.scheduleJob(job, trig);
    sched.start();

    } catch (Exception e) {
    log.info("Exception in Init Servlet" + e);
    }
    }


     */

    protected final Log log = LogFactory.getLog(PhoneSynchronizerJob.class);
    private SchedulerFactory sf = null;
    private Scheduler sched = null;
    private JobDetail job = null;
    private boolean firstTime = true;
    private SimpleTrigger trigger = null;
    private SynchUtils syn = null;

    @Override
    public void init(ServletConfig cfg) throws javax.servlet.ServletException {
        try {
            super.init(cfg);
            sf = (SchedulerFactory) getServletContext().getAttribute(QuartzInitializerListener.QUARTZ_FACTORY_KEY);
            sched = sf.getScheduler();
            job = new JobDetail("JobTest1", "Group1", PhoneSynchronizerJob.class);
            syn = new SynchUtils();
            //syn.openConnection();
            syn.initDataSource();
            sched.getContext().put("utilClass", syn);
        } catch (Exception ex) {
            log.error("Exception in Init", ex);
            throw new ServletException("Error in Init =>" + ex.getMessage());
        }
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
        PrintWriter out = null;
        try {
            out = resp.getWriter();
            out.println("Hello, world! Testiong !!!");

        } catch (IOException ex) {
            log.error("Exception in Get Servlet", ex);
        } finally {
            out.close();
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String command = req.getParameter("cmd");
            String message = "";
            if ("RUN_JOB".equals(command)) {
                try {
                    long startTime = System.currentTimeMillis() + 5000L;
                    Date startDate = new Date(startTime);
                    if (firstTime) {
                        trigger = new SimpleTrigger("myTrigger", "Group1", startDate, null, 0, 0L);
                        sched.scheduleJob(job, trigger);
                        firstTime = false;
                        message = "Job was scheduled to Run at " + startDate + " First Time";
                    } else {
                        if (!PhoneSynchronizerJob.isRunning()) {
                            log.info("Scheduele Job => " + startDate);
                            sched.deleteJob("JobTest1", "Group1");
                            trigger.setStartTime(startDate);
                            //trigger = new SimpleTrigger("myTrigger", "Group1", startDate, null, 0, 0L);
                            //sched.rescheduleJob("myTrigger", "Group1", trigger);
                             sched.scheduleJob(job, trigger);
                            message = "Job was scheduled to Run at " + startDate;
                        } else {
                            log.info("The Request was canceeled due that Job is running");
                            message = "Sorry, we can't schedule the Job, because is running still";
                        }
                    }
                } catch (Exception ex) {
                    log.info("Exception  -->", ex);
                }
            } else {
                message = "Commnd Unknow";
            }
            req.setAttribute("msg", message);
            RequestDispatcher rd = req.getRequestDispatcher("/application/index.jsp");
            rd.forward(req, resp);
        } catch (Exception ex) {
            log.info("Exception in Run Job Servlet", ex);
        }
    }

    @Override
    public void destroy() {
        try {
            //syn.closeConnection();
            syn.detroyDataSource();
        } catch (Exception e) {
            log.info("Exception in Destroy " + e);
        }
    }
}
